<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>刮刮卡</title>
  <style>
    .card {
      width: 200px;
      height: 100px;
      border: 1px solid #ccc;
      margin: 200px auto;
      color: red;
      position: relative;
    }

    .card span {
      position: absolute;
      width: 100%;
      height: 100%;
      text-align: center;
      font-size: 50px;
      line-height: 100px;
    }

    canvas {
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>

</head>

<body>
  <div class="card">
    <span id="span">200元</span>
    <canvas id="canvas"></canvas>
  </div>

  <script>
    var canvas = document.getElementById('canvas')
    init();

    function init() {
      canvas.width = 200;
      canvas.height = 100;
      var ctx = canvas.getContext('2d')
      drawCover(ctx)
      drawStroke(ctx)
      productResult()
    }

    // 往 span 填充内容
    function productResult(params) {
      var span = document.getElementById('span')
      var arr = ['100元', '100元', '200元', '200元', '300元', '400元', '谢谢', '谢谢', '谢谢', '谢谢',]
      var text = arr[randomInt(0, arr.length - 1)]
      span.innerHTML = text;
    }

    function randomInt(from, to) {
      return parseInt(Math.random() * (to - from + 1) + from)
    }

    // 绘制覆盖层
    function drawCover(ctx) {
      ctx.save();
      ctx.fillStyle = "rgb(100, 100, 100)"
      ctx.fillRect(0, 0, 200, 100)
      ctx.restore();
    }

    function drawStroke(ctx) {

      canvas.onmousedown = function (e) {
        // 鼠标坐标
        var downX = e.offsetX;
        var downY = e.offsetY;

        ctx.beginPath();
        ctx.globalCompositeOperation = 'destination-out'
        ctx.lineWidth = 20;
        ctx.moveTo(downX, downY)

        canvas.onmousemove = function (e) {
          var x = e.offsetX;
          var y = e.offsetY;
          ctx.lineTo(x, y);
          ctx.stroke();
        }

      }
      canvas.onmouseup = function () {
        canvas.onmousemove = null;
      }
    }
  </script>

</body>

</html>